<?php

namespace App\Models;

// use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Sanctum\HasApiTokens;
use Spatie\Activitylog\Traits\LogsActivity;
use Spatie\Activitylog\LogOptions;

class User extends Authenticatable
{
    use HasApiTokens, HasFactory, Notifiable, LogsActivity;

    /**
     * The attributes that are mass assignable.
     *
     * @var array<int, string>
     */
    protected $fillable = [
        'openid',
        'unionid',
        'nickname',
        'password',
        'avatar',
        'phone',
        'gender',
        'city',
        'province',
        'country',
        'language',
        'last_login_at',
        'is_active',
    ];

    /**
     * The attributes that should be hidden for serialization.
     *
     * @var array<int, string>
     */
    protected $hidden = [
        'password',
        'remember_token',
    ];

    /**
     * The attributes that should be cast.
     *
     * @var array<string, string>
     */
    protected $casts = [
        'last_login_at' => 'datetime',
        'is_active' => 'boolean',
    ];

    /**
     * 准备日期用于数组/JSON序列化
     */
    protected function serializeDate(\DateTimeInterface $date): string
    {
        return $date->format('Y-m-d H:i:s');
    }

    /**
     * 用户创建的房间
     */
    public function createdRooms()
    {
        return $this->hasMany(Room::class, 'creator_id');
    }

    /**
     * 用户的所有房间（创建的房间）
     */
    public function rooms()
    {
        return $this->hasMany(Room::class, 'creator_id');
    }

    /**
     * 用户加入的房间
     */
    public function joinedRooms()
    {
        return $this->belongsToMany(Room::class, 'room_members')
                    ->withPivot(['role', 'joined_at', 'last_active_at', 'is_active', 'settings'])
                    ->withTimestamps();
    }

    /**
     * 用户的订单
     */
    public function orders()
    {
        return $this->hasMany(Order::class);
    }

    /**
     * 用户收藏的菜品
     */
    public function favoriteDishes()
    {
        return $this->belongsToMany(Dish::class, 'user_favorites');
    }

    /**
     * 活动日志配置
     */
    public function getActivitylogOptions(): LogOptions
    {
        return LogOptions::defaults()
            ->logOnly(['nickname', 'phone', 'email', 'status'])
            ->logOnlyDirty()
            ->dontSubmitEmptyLogs();
    }
}
